const {emptyData} = require("../utils/misc")
const ObjectId = require('mongodb').ObjectId
const router = require('koa-router')();
const mongo = require('../compents/mongo')
const {postLogData} =require("../utils/misc")
router.prefix('/discoupon')

router.get('/list', async ctx => {
    postLogData("请求优惠券")
    let { page,name,type,_id} = ctx.query
    let where = {name,type,_id:ObjectId(_id)}
    name?"":delete where.name
    type?"":delete where.type
    _id?"":delete where._id
    const res = await mongo.find('discoupon', {page:page*1,where})
    const total = res.length
    if (res) {
        ctx.body = { data: res, code: 20000, total, message: "数据请求成功" }
    } else {
        ctx.body = {data:res, code: 50001, message: "数据请求失败" }
    }
})

router.post('/save', async ctx => {
    postLogData("新增优惠券")
    let camData = ctx.request.body
    camData= emptyData(camData,["name","avaCourse","minUse","faceValue","platform","validity","state","type","num","limit"])
    const res = await mongo.insertOne('discoupon', { ...camData})
    if (res.insertedId) {
        ctx.body = { data: res, code: 20000, message: "数据插入成功" };
    } else {
        ctx.body = { data: res, code: 50002, message: "数据插入失败" };
    }
})
// 修改数据库
router.post('/change', async ctx => {
    postLogData("修改优惠券")
    const { _id } = ctx.request.body
    const update = ctx.request.body
    delete update._id
    const res = await mongo.updateOne('discoupon', { where: { _id: ObjectId(_id) }, update })
    if (res.modifiedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据修改成功" };
    } else {
        ctx.body = { data: res, code: 50004, message: "数据修改失败" };
    }
})

// 删除单挑数据
router.get('/delOne', async ctx => {
    postLogData("单删优惠券")
    const { _id } = ctx.query
    const res = await mongo.deleteOne('discoupon', { _id: ObjectId(_id) })
    if (res.deletedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据删除成功" };
    } else {
        ctx.body = { data: res, code: 50005, message: "数据删除失败" };
    }
})
// 删除多条数据   
router.get('/delMany', async ctx => {
    postLogData("多删优惠券")
    let { ids } = ctx.query
    ids = JSON.parse(ids)
    console.log(ids);
    const res = await mongo.deleteMany('discoupon', ids)
    if (res.deletedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据批量删除成功" };
    } else {
        ctx.body = { data: res, code: 50006, message: "数据批量删除失败" };
    }
})

module.exports = router 